﻿using Futajma.MigrationStudio.DataDefinition;
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Futajma.MigrationStudio.SharePointPersistance
{
    public enum TargetAudience
    {
        All,
        MigrationConsultant,
        ContentOwner
    }
    public class SharePoint2010ApplicationConfiguration
    {
        public class UpdateFeedItem
        {
            public bool Valid { get; set; }
            public string UpdateFeed { get; set; }
            public int ItemId { internal set; get; }
        }
              

        public static void UploadLogFile(string filePath)
        {
            using (ExtendedClientContext clientContext = new ExtendedClientContext(Settings.MigrationPortalUrl))
            {
                Web web = clientContext.Web;
                var info = new FileInfo(filePath);

                var filename = string.Format("{0}_{1}", info.LastWriteTime.ToString("yyyy_MM_dd_hh_mm_ss"), Path.GetFileName(filePath));
                var chars = Path.GetInvalidPathChars();
                filename = new string(filename.Select(c => chars.Contains(c) ? '_' : c).ToArray());

                FileCreationInformation newFile = new FileCreationInformation();
                newFile.Content = System.IO.File.ReadAllBytes(filePath);
                newFile.Overwrite = true;
                newFile.Url = filename;

                List docs = web.Lists.GetByTitle(Settings.ApplicationUpdateLogList);

                Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
                clientContext.Load(uploadFile);
                clientContext.ExecuteQuery();
            }
        }

        public void DownloadAttachedFileFromListItem(int itemId, string attachmentName, string downloadLocation)
        {
            using (ExtendedClientContext clientContext = new ExtendedClientContext(Settings.MigrationPortalUrl))
            {
                clientContext.Load(clientContext.Web);
                clientContext.ExecuteQuery();

                var webPath = clientContext.Web.ServerRelativeUrl == "/" ? "" : clientContext.Web.ServerRelativeUrl;

                string attachmentPath = string.Format("{0}/lists/{1}/Attachments/{2}/{3}", webPath,
                    Settings.ApplicationUpdateListTitle, itemId, Path.GetFileName(attachmentName));
                var fileInformation = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, attachmentPath);
                IList<byte> content = new List<byte>();
                int b;
                while ((b = fileInformation.Stream.ReadByte()) != -1)
                {
                    content.Add((byte)b);
                }

                
                //var downloadFileName = Path.Combine(downloadLocation, attachmentName);
                System.IO.File.WriteAllBytes(downloadLocation, content.ToArray());
                fileInformation.Stream.Close();
            }
        }


        public UpdateFeedItem CheckUpdateFeed(TargetAudience targetAudience, string currentVersion)
        {
            var feedItem = new UpdateFeedItem() { Valid = false };
            using (ExtendedClientContext clientContext = new ExtendedClientContext(Settings.MigrationPortalUrl))
            {

                Web oWebsite = clientContext.Web;
                ListCollection collList = oWebsite.Lists;

                List oList = collList.GetByTitle(Settings.ApplicationUpdateListTitle);

                CamlQuery camlQuery = new CamlQuery();
                camlQuery.ViewXml = string.Format(Settings.ApplicationUpdateItemQuery, currentVersion, targetAudience);

                ListItemCollection collListItem = oList.GetItems(camlQuery);

                clientContext.Load(oWebsite);
                clientContext.Load(oList);
                clientContext.Load(collListItem);

                clientContext.ExecuteQuery();

                if (collListItem.Count > 0)
                {
                    var webPath = oWebsite.ServerRelativeUrl == "/" ? "":oWebsite.ServerRelativeUrl;

                    string attachmentPath = string.Format("{0}/lists/{1}/Attachments/{2}/{3}", webPath,
                        Settings.ApplicationUpdateListTitle, collListItem[0].Id, Settings.ApplicationUpdateItemFileName);

                    var fileInformation = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, attachmentPath);

                    using (var reader = new StreamReader(fileInformation.Stream))
                    {
                        feedItem.UpdateFeed = reader.ReadToEnd();
                        feedItem.ItemId = collListItem[0].Id;
                        feedItem.Valid = true;
                    }
                }
                return feedItem;
            }
        }

        //public void DownloadAttachedFileFromListItem(string siteUrl, string webName, int itemId, string attachmentName, string listName, string downloadLocation)
        //{
        //    using (ClientContext clientContext = new ClientContext(siteUrl))
        //    {
        //        string attachmentPath = string.Format("/{0}/lists/{1}/Attachments/{2}/{3}", webName, listName, itemId, Path.GetFileName(attachmentName));
        //        var fileInformation = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, attachmentPath);
        //        IList<byte> content = new List<byte>();
        //        int b;
        //        while ((b = fileInformation.Stream.ReadByte()) != -1)
        //        {
        //            content.Add((byte)b);
        //        }
        //        var downloadFileName = Path.Combine(downloadLocation, attachmentName);
        //        System.IO.File.WriteAllBytes(downloadFileName, content.ToArray());
        //        fileInformation.Stream.Close();
        //    }
        //}


        public static GovernanceData LoadGovernanceData()
        {

            ExtendedClientContext clientContext = new ExtendedClientContext(Settings.MigrationPortalUrl);

            Web oWebsite = clientContext.Web;
            ListCollection collList = oWebsite.Lists;

            List oList = collList.GetByTitle(Settings.ConfigurationListTitle);

            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = string.Format("<View><Query><Where><Eq>" +
                "<FieldRef Name='Title'/><Value Type='Text'>{0}</Value>" +
                "</Eq></Where></Query></View>", Settings.GovernanceDataItemTitle);

            ListItemCollection collListItem = oList.GetItems(camlQuery);
            clientContext.Load(oList);
            clientContext.Load(collListItem,
                items => items.IncludeWithDefaultProperties(
                item => item.DisplayName));

            clientContext.ExecuteQuery();

            if (collListItem.Count > 0)
            {
                var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, (string)collListItem[0]["FileRef"]);

                XmlSerializer serializer = new XmlSerializer(typeof(GovernanceData));

                using (XmlReader reader = XmlReader.Create(fileInfo.Stream))
                {
                    var governanceData = (GovernanceData)serializer.Deserialize(reader);
                    return governanceData;
                }
            }
            else
            {
                return null;
            }
        }
    }
}
